const express = require("express");
const multer = require("multer");
const crypto = require("crypto");
const path = require("path");
const fs = require("fs");
const util = require("util");
const app = express();
const port = 3333;

const publicUrl = path.resolve("service/public");
const uploadsFile = path.join(publicUrl,"uploads");

app.use(express.static(publicUrl)); 


// 设置存储配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const stat = util.promisify(fs.stat);

    stat(uploadsFile)
      .catch(() => {
        fs.mkdirSync(uploadsFile, { recursive: true });
      })
      .finally(() => {
        cb(null, uploadsFile);
      });
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  },
});

const upload = multer({ storage: storage });

app.post("/upload", upload.single("exeFile"), (req, res) => {

  if (!req.file) {
    return res.status(400).send("No file uploaded.");
  }

  // 计算文件的 SHA-512 哈希值
  const hash = crypto.createHash("sha512");

  //创建流读取文件
  const input = fs.createReadStream(req.file.path);

  input.on("data", (data) => {
    hash.update(data);
  });
  input.on("end", () => {
    const fileHash = hash.digest("hex");

    //处理文件名
    const originalVersionNameList = req.file.originalname
    .split(" ")
    .pop()
    .split(".")
    
    originalVersionNameList.pop();
    
    // 生成 latest.yml 内容
    const latestYmlContent = 
    `name: ${req.file.originalname}  
version: ${originalVersionNameList.join('.')}
files:  
  - url: http://localhost:${port}/uploads/${req.file.originalname}  
    sha512: ${fileHash}`; 


    // 定义latest.yml 存储位置
    const latestYmlPath = path.join(uploadsFile, "latest.yml");

    // 写入 latest.yml 文件
    fs.writeFile(latestYmlPath, latestYmlContent, (err) => {
      if (err) {
        return res.status(500).send("Failed to write latest.yml.");
      }
      res.send("File uploaded and latest.yml generated successfully.");
    });
  });
  input.on("error", (err) => {
    res.status(500).send("Error reading the file.");
  });
});

app.get("/getLatestYml",(req,res)=>{

  const latestYmlPath = path.join(uploadsFile, 'latest.yml');
  
  const stat = util.promisify(fs.stat);

    stat(latestYmlPath)
      .then(()=>{
        res.sendFile(latestYmlPath);  
      })
      .catch(() => {
        res.status(500).send("未找到latest.yml文件");
      })
 
})

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
